#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <mpv/client.h>

#include "libmpv.h"
#include "parse.h"
#include "event.h"

int
main(void)
{
	char buf[BUFSIZ];
	int flags;
	ssize_t n;

	if (-1 == (flags = fcntl(0, F_GETFL, 0)))
		perror("fcntl");
	if (-1 == fcntl(0, F_SETFL, flags | O_NONBLOCK))
		perror("fcntl");

	if (libmpv_init()) {
		fprintf(stderr, "Failed to initialize libmpv");
		exit(EXIT_FAILURE);
	}

	while (1) {
		errno = 0;
		n = read(0, buf, BUFSIZ);
		if (-1 == n) {
			if (EAGAIN != errno) {
				perror("read");
			}
		} else {
			if (n > 0) {
				buf[n >= BUFSIZ ? BUFSIZ-1 : n] = '\0';
				parse(buf);
			}
		}
		event_handler();
	}

	return 0;
}
